import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_common_app/event_bus/audio_bottom_event.dart';
import 'package:flutter_common_app/event_bus/global_event_bus.dart';
import 'package:flutter_common_app/event_bus/tabbar_event.dart';
import 'package:flutter_common_app/pages/tab/discover_tab.dart';
import 'package:flutter_common_app/pages/tab/mine_tab.dart';
import 'package:flutter_common_app/pages/tab/dynamic_tab.dart';
import 'package:flutter_common_app/provider_model/audio_model.dart';
import 'package:flutter_common_app/router/routes.dart';
import 'package:flutter_common_app/utils/common_util/log_util.dart';
import 'package:flutter_common_app/utils/user_util.dart';
import 'package:flutter_common_app/widgets/app_bar/custom_app_bar.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:provider/provider.dart';

class IndexPage extends StatefulWidget {
  @override
  _IndexPageState createState() => _IndexPageState();
}

class _IndexPageState extends State<IndexPage>
    with TickerProviderStateMixin, WidgetsBindingObserver {
  TabController tabController;

  List<Widget> tabViews = [
    DiscoverTab(),
    MineTab(),
    DynamicTab(),
  ];

  List<String> tabsTitle = ['发现', '我的', '动态'];

  List<Widget> tabsWidget = [];

  int currentIndex = 0;

  StreamSubscription<AudioBottomEvent> streamSubscription;

  AudioModel audioModel;

  @override
  void initState() {
    WidgetsBinding.instance.addObserver(this);

    tabController = TabController(
      initialIndex: currentIndex,
      length: tabsTitle.length,
      vsync: this,
    );

    tabController.addListener(() {
      setState(() {
        currentIndex = tabController.index;
      });
    });

    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      audioModel = Provider.of<AudioModel>(context, listen: false)
        ..initSongsData();
    });

    streamSubscription =
        GlobalEventBus().bus.on<AudioBottomEvent>().listen((event) {
      LogUtil.v('GlobalEventBus-:setAudioBottomWidgetStatus');
      audioModel.setAudioBottomWidgetStatus(event.hide);
    });
    super.initState();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    print('当前state为：$state');
  }

  @override
  void dispose() {
    tabController.dispose();
    streamSubscription.cancel();
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: CustomAppBar(
        Row(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [buildTabItem(0), buildTabItem(1), buildTabItem(2)],
        ),
      ),
      body: TabBarView(
        children: tabViews,
        controller: tabController,
        // physics: NeverScrollableScrollPhysics(),
      ),
    );
  }

  Widget buildTabItem(int index) {
    return GestureDetector(
      onTap: () {
        if (index == 1 && !UserUtil.isLogin(context)) {
          Routes.navigateTo(context, Routes.login);
          return;
        }
        setState(() {
          tabController.index = index;
        });
      },
      behavior: HitTestBehavior.opaque,
      child: Container(
        width: 120.w,
        margin: EdgeInsets.symmetric(horizontal: 10.w),
        decoration: BoxDecoration(),
        child: Text(
          tabsTitle[index],
          textAlign: TextAlign.center,
          style: TextStyle(
            color: currentIndex == index ? Colors.black87 : Colors.black45,
            fontSize: currentIndex == index ? 36.sp : 32.sp,
            fontWeight:
                currentIndex == index ? FontWeight.w600 : FontWeight.w400,
          ),
        ),
      ),
    );
  }
}
